﻿using ERP_SaaS_WinForm.生产计划_派单_车间.ProductPlan;
using ERP_SaaS_WinForm.生产计划_派单_车间.apiResquest;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_SaaS_WinForm.生产计划_派单_车间
{
    public partial class UpdateProductPlan : Form
    {
        private PlanData currentPlanData;
        private HttpClient httpClient;

        [DllImport("gdi32.dll")]
        private static extern IntPtr CreateRoundRectRgn(int nLeftRect, int nTopRect, int nRightRect, int nBottomRect, int nWidthEllipse, int nHeightEllipse);

        public UpdateProductPlan(PlanData planData)
        {
            InitializeComponent();
            currentPlanData = planData;
            httpClient = new HttpClient();
            InitializeModernDesign();
            LoadPlanData();
        }

        private void InitializeModernDesign()
        {
            this.BackColor = Color.FromArgb(245, 248, 250);
            this.StartPosition = FormStartPosition.CenterScreen;
            this.Text = "修改生产计划";
            this.Size = new Size(800, 600);
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
        }

        private void LoadPlanData()
        {
            try
            {
                // 调试：输出接收到的数据
                Console.WriteLine($"接收到的数据: planId={currentPlanData.planId}, planCode={currentPlanData.planCode}, planName={currentPlanData.planName}");
                
                // 加载当前计划数据到表单
                txtPlanCode.Text = currentPlanData.planCode ?? "";
                txtPlanName.Text = currentPlanData.planName ?? "";
                txtproname.Text = currentPlanData.productName ?? "";
                txtProcode.Text = currentPlanData.productCode ?? "";
                txtspecifi.Text = currentPlanData.specification ?? "";
                txtunit.Text = currentPlanData.unitName ?? "";
                txtPlannum.Text = currentPlanData.planNum.ToString();
                txtOrderCode.Text = currentPlanData.salesOrderId?.ToString() ?? "";

                // 设置来源类型下拉框
                var resourceList = new List<OrderSource>
                {
                    new OrderSource { Value = 0, Name = "请选择来源类型" },
                    new OrderSource { Value = 1, Name = "销售订单" },
                    new OrderSource { Value = 2, Name = "库存备货" },
                    new OrderSource { Value = 3, Name = "其他" }
                };
                cboResource.DataSource = resourceList;
                cboResource.DisplayMember = "Name";
                cboResource.ValueMember = "Value";
                cboResource.SelectedValue = currentPlanData.resource;

                // 设置日期 - 使用更安全的日期处理
                try
                {
                    if (currentPlanData.planStart.HasValue && currentPlanData.planStart.Value != DateTime.MinValue)
                    {
                        dtpStart.text = currentPlanData.planStart.Value.ToString("yyyy-MM-dd");
                    }
                    else
                    {
                        dtpStart.text = DateTime.Now.ToString("yyyy-MM-dd");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"设置开工时间失败: {ex.Message}");
                    dtpStart.text = DateTime.Now.ToString("yyyy-MM-dd");
                }

                try
                {
                    if (currentPlanData.planEnd.HasValue && currentPlanData.planEnd.Value != DateTime.MinValue)
                    {
                        dtpComple.text = currentPlanData.planEnd.Value.ToString("yyyy-MM-dd");
                    }
                    else
                    {
                        dtpComple.text = DateTime.Now.ToString("yyyy-MM-dd");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"设置完工时间失败: {ex.Message}");
                    dtpComple.text = DateTime.Now.ToString("yyyy-MM-dd");
                }

                try
                {
                    if (currentPlanData.requireDate.HasValue && currentPlanData.requireDate.Value != DateTime.MinValue)
                    {
                        dtpRequireDate.text = currentPlanData.requireDate.Value.ToString("yyyy-MM-dd");
                    }
                    else
                    {
                        dtpRequireDate.text = DateTime.Now.ToString("yyyy-MM-dd");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"设置需求日期失败: {ex.Message}");
                    dtpRequireDate.text = DateTime.Now.ToString("yyyy-MM-dd");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("加载计划数据失败: {0}", ex.Message), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                // 禁用修改按钮，防止重复点击
                btnUpdate.Enabled = false;
                btnUpdate.Text = "修改中...";
                
                if (ValidateInput())
                {
                    // 安全地解析日期
                    DateTime? planStart = null;
                    DateTime? planEnd = null;
                    DateTime? requireDate = null;

                    try
                    {
                        if (!string.IsNullOrEmpty(dtpStart.text))
                        {
                            if (DateTime.TryParse(dtpStart.text, out DateTime start))
                            {
                                planStart = start;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"解析开工时间失败: {ex.Message}");
                    }

                    try
                    {
                        if (!string.IsNullOrEmpty(dtpComple.text))
                        {
                            if (DateTime.TryParse(dtpComple.text, out DateTime end))
                            {
                                planEnd = end;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"解析完工时间失败: {ex.Message}");
                    }

                    try
                    {
                        if (!string.IsNullOrEmpty(dtpRequireDate.text))
                        {
                            if (DateTime.TryParse(dtpRequireDate.text, out DateTime require))
                            {
                                requireDate = require;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"解析需求日期失败: {ex.Message}");
                    }

                    var updateData = new
                    {
                        planId = currentPlanData.planId,
                        planCode = txtPlanCode.Text.Trim(),
                        planName = txtPlanName.Text.Trim(),
                        resource = cboResource.SelectedValue != null ? (int)cboResource.SelectedValue : 0,
                        productName = txtproname.Text.Trim(),
                        productCode = txtProcode.Text.Trim(),
                        specification = txtspecifi.Text.Trim(),
                        unitName = txtunit.Text.Trim(),
                        planNum = int.TryParse(txtPlannum.Text.Trim(), out int num) ? num : 0,
                        planStart = planStart,
                        planEnd = planEnd,
                        requireDate = requireDate,
                        planState = currentPlanData.planState ?? 0,
                        createName = currentPlanData.createName ?? "",
                        createDate = currentPlanData.createDate ?? DateTime.Now,
                        productId = currentPlanData.productId,
                        state = currentPlanData.state ?? 0,
                        salesOrderId = int.TryParse(txtOrderCode.Text.Trim(), out int orderId) ? orderId : 0
                    };

                    var apiResponse = await ApiRequestHelper.PostAsync<dynamic>("api/Plan/UpdatePlan", updateData);

                    if (apiResponse.Success)
                    {
                        ApiRequestHelper.ShowSuccess("生产计划修改成功！");
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        ApiRequestHelper.ShowError($"请求失败: {apiResponse.Message}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("修改生产计划失败: {0}", ex.Message), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复按钮状态
                btnUpdate.Enabled = true;
                btnUpdate.Text = "修改";
            }
        }

        private bool ValidateInput()
        {
            if (string.IsNullOrWhiteSpace(txtPlanCode.Text))
            {
                MessageBox.Show("请输入计划编号", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtPlanCode.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txtPlanName.Text))
            {
                MessageBox.Show("请输入计划名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtPlanName.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txtproname.Text))
            {
                MessageBox.Show("请输入产品名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtproname.Focus();
                return false;
            }

            if (cboResource.SelectedValue == null || (int)cboResource.SelectedValue == 0)
            {
                MessageBox.Show("请选择来源类型", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cboResource.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txtPlannum.Text) || !int.TryParse(txtPlannum.Text, out int num) || num <= 0)
            {
                MessageBox.Show("请输入有效的计划数量", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtPlannum.Focus();
                return false;
            }

            return true;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }



        private void btnProductName_Click(object sender, EventArgs e)
        {
            try
            {
                var selectProductForm = new SelectProduct();
                if (selectProductForm.ShowDialog() == DialogResult.OK)
                {
                    var selectedProduct = selectProductForm.SelectedProduct;
                    if (selectedProduct != null)
                    {
                        txtproname.Text = selectedProduct.ProductName ?? "";
                        txtProcode.Text = selectedProduct.ProductCode ?? "";
                        txtspecifi.Text = selectedProduct.Specification ?? "";
                        txtunit.Text = selectedProduct.UnitName ?? "";
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("打开产品选择窗口失败: {0}", ex.Message), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnOrderNumber_Click(object sender, EventArgs e)
        {
            try
            {
                var selectSaleForm = new SelectSale();
                if (selectSaleForm.ShowDialog() == DialogResult.OK)
                {
                    var selectedSale = selectSaleForm.SelectedSale;
                    if (selectedSale != null)
                    {
                        txtOrderCode.Text = selectedSale.SalesOrderId.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("打开销售订单选择窗口失败: {0}", ex.Message), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


    }


}
